/*
 * @Author: xiaosihan 
 * @Date: 2023-08-10 11:24:00 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-12-25 08:36:13
 */

import editorStore from "../../editorStore";
import { autorun, toJS } from "mobx";
import { useEffect, useRef, useState } from "react";
import styles from "./toolClothColor.module.less";
import clsx from "clsx";
import { divide, get, isArray, isEmpty, isUndefined, throttle } from "lodash";
import textureManager from "@/editorComponent/textureManager";
import designEditor from "@/editorComponent/designEditor";
import { Button, Tooltip } from "antd";
import { SketchPicker } from "react-color";
import ColorPick from "../ColorPick/ColorPick";
import preview3DRenderer from "@/editorComponent/preview3DRenderer";

interface Iprops {
}

// 商品颜色
export default function ToolClothColor() {

  const showTop = useRef(false);
  const [visible, setVisible] = useState(true);
  const [colors, setColors] = useState<Array<{ [key: string]: string } & { color: `#${string}` }>>([]);
  const [disable, setDisable] = useState(false);
  const [activeColor, setActiveColor] = useState("#ffffff");
  const [fillType, setfillType] = useState(-1); // 印刷工艺 0 是满版印 1是局部印

  useEffect(() => autorun(() => {
    const { activeComponent, goodsData, design_data } = editorStore;

    const background = get(design_data, ['designData', activeComponent, "background"], "#ffffff");

    const fillType = get(goodsData, ["fillType"]);
    setfillType(isUndefined(fillType) ? -1 : fillType);

    if (fillType === 0) {
      setActiveColor(background);
    } else if (fillType === 1) {
      setActiveColor(design_data.colorValue);
    }
    const colors = get(goodsData, ["colors"]) || [];
    setColors(colors);

    //如果是局部打印就把 模型的内面设置为当前颜色
    if (fillType === 0) {
      preview3DRenderer.setBackColor("#ffffff");
    } else if (fillType === 1) {
      const { colorValue } = design_data;
      preview3DRenderer.setBackColor(colorValue);
    }

  }, { delay: 30 }), []);

  useEffect(() => autorun(() => {
    const { pickerColor, activeComponent } = editorStore;
    if (showTop.current && pickerColor && activeComponent) {
      modifyColor(pickerColor, pickerColor as `#${string}`);
      designEditor.setColor(pickerColor as string, pickerColor as `#${string}`, [activeComponent]);
    }
  }, { delay: 30 }), []);

  //修改颜色
  const modifyColor = (color: string, colorValue: `#${string}`) => {
    setActiveColor(color);
    editorStore.setDesignColor(color, colorValue);
  }

  // 应用到全部
  const applyAll = async () => {
    const { activeComponent } = editorStore;
    const design_data = toJS(editorStore.design_data.designData);
    for (let name in design_data) {
      if (name !== activeComponent && !isEmpty(design_data[name])) {
        design_data[name].background = activeColor;
        editorStore.modifyDesignData(design_data[name], name);
        await textureManager.updataTextByFabricJSON(name, design_data[name]);
        const textCanvasCtx = textureManager.getContext(name);
        const fabricMark = designEditor.fabricMarkMap.get(name);
        if (fabricMark && textCanvasCtx) {
          fabricMark.clip(textCanvasCtx, 1024, 1);
        }
      }
    }
    editorStore.updataTime();
    designEditor.setHasChange(true);
  }

  return (
    <div className={clsx(styles.toolClothColor, visible && styles.visible)} >

      {
        // 满版打印是拾色器
        fillType === 0 &&
        <div className={clsx(styles.toolTextColor, visible && styles.visible, disable && styles.disable)} >
          <span className={styles.lable} >背景颜色</span>

          <Tooltip
            title={
              <div className={styles.color_picker} >
                <SketchPicker
                  className={styles.SketchPicker}
                  color={activeColor}
                  onChange={(color: any) => {
                    modifyColor(color.hex as `#${string}`, color.hex as `#${string}`);
                    const { activeComponent } = editorStore;
                    designEditor.setColor(color.hex as string, color.hex as `#${string}`, [activeComponent]);
                  }}

                />
                <ColorPick />
              </div>
            }
            onOpenChange={open => {
              showTop.current = open;
            }}
            trigger={['click']}
            color={"#00000000"}
            placement="bottom"
          >
            <span
              className={styles.colorBlock}
              style={{ backgroundColor: activeColor }}
            ></span>
          </Tooltip>
          &nbsp;
          &nbsp;
          &nbsp;
          &nbsp;
          &nbsp;
          &nbsp;
          &nbsp;
          &nbsp;
          &nbsp;
          &nbsp;
          &nbsp;
          <Button
            type="primary"
            size="small"
            className={styles.apply_all}
            onClick={applyAll}
          >应用到全部面</Button>
        </div>

      }
      {
        // 局部打印是选颜色块
        fillType === 1 &&
        (isArray(colors) ? colors : []).map((c, i) => {
          return (
            <Tooltip
              key={i}
              title={c.cn}
              placement="top"
              mouseLeaveDelay={0}
              mouseEnterDelay={0}
            >
              <span
                className={clsx(styles.colorBlock, c.color === activeColor && styles.active)}
                style={{ backgroundColor: c.color }}
                onClick={async () => {
                  modifyColor(c.cn, c.color);
                  const components = Object.keys(editorStore.design_data.designData);
                  designEditor.setColor(c.cn, c.color as `#${string}`, components);
                }}
              >
              </span>
            </Tooltip>
          );
        })
      }

    </div>

  );

}